﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RuleCode.Table;
using RuleCode.Common;
using System.Data;
using System.Drawing;



namespace chatblog.usercate
{
    public partial class chatroom : System.Web.UI.Page
    {
        #region 页面下载
        protected void Page_Load(object sender, EventArgs e)
        {
            //(AppDomain .CurrentDomain .Id); 
            //ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "ddd", "<script type=\"text/javascript\"> alert('"+ this.User .Identity .Name +"');</script>", false);
            AjaxPro.Utility.RegisterTypeForAjax(typeof(chatroom));
            cbuser.dealcookie();
            if (AliApi.appUserId != string.Empty && AliApi.appUserId != null)
            {
                cbuser user = cbuser.Find("cbuserid='" + AliApi.appUserId + "'");
                if (user.Count > 0)
                {
                    if (IsPostBack == false && user.chatIsOnLine.Value == RuleCode.Enum.BooleanEnum.Yes)
                    {
                        Util.useLoginOut = false;
                        string scriptStr = "alert('对不起，您的当前用户已经在其他地方打开该聊天室！不能再打开了');document.location .href='../login/ChatSetup.aspx'; ";
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "hasLogin", "<script type=\"text/javascript\">" + scriptStr + "</script>", false);

                        return;
                    }
                    else
                    {

                        user.cbChatAddress.Value = "ip=" + Request.UserHostAddress + ";domainid=" + AppDomain.CurrentDomain.Id.ToString() + ";name=" + AppDomain.CurrentDomain.FriendlyName;
                        user.chatIsOnLine.Value = RuleCode.Enum.BooleanEnum.Yes;
                        user.isonline.Value = RuleCode.Enum.BooleanEnum.Yes;
                        user.Modify();
                    }
                }
            }
            if (!IsPostBack)
            {
                BindUserCate();
            }
        }
        #endregion

        #region 当前用户相关
        [AjaxPro .AjaxProperty ]
        public  string currentUserID
        {
            get
            {
                return AliApi.appUserId;
            }
            
        }
         
        [AjaxPro .AjaxMethod ]
        public string GetCurrentUserID()
        {
            return currentUserID ;
        }

        private static string systemUserId = "系统消息";
        #endregion

        #region 聊天窗口Ajax
        [AjaxPro.AjaxMethod]
        public string GetNewGuid()
        {
            return Guid.NewGuid().ToString("N");
        }

        [AjaxPro.AjaxMethod]
        public string SendMyEmail()
        {

            //MailHelper.SendEmail("dingyuliang@rulecode.com", null, "异步", "ceshi", true);

            RuleCode.Common.Cryptography cc = new RuleCode.Common.Cryptography();
            cc.DesEncrypt("dingyuliang", "dingyuliang");
            return cc.DesDecrypt(cc.DesEncrypt("dingyuliang", "dingyuliang"), "dingyuliang");

        }

        [AjaxPro.AjaxMethod]
        public void InsertNewMessage(string user_to, string content, int ispublic)
        {
            cbChatInfo chatinfo = new cbChatInfo();
            chatinfo.Init(0);
            chatinfo.New();
            chatinfo.cbChatInfoId.Value = chatinfo.GetRecID().ToString();
            chatinfo.user_from.Value = currentUserID;
            chatinfo.user_to.Value = user_to;
            chatinfo.sendTime.Value = DateTime.Now;
            chatinfo.ispublic.Value = ispublic;
            chatinfo.content.Value = content;
            chatinfo.Insert();
        }

        [AjaxPro.AjaxMethod]
        public string ValidateUser(string userid, string pass)
        {
            string filter = "cbuserid='" + userid + "' and cbpassword='" + pass + "'";
            RuleCode.Table.cbuser cbuser = cbuser.Find(filter);
            if (cbuser.Count > 0)
            {
                AliApi .appUserId   = userid;
                return userid;
            }
            return "";
        }

        /// <summary>
        /// 获取私人聊天记录
        /// </summary>
        /// <param name="user_from"></param>
        /// <returns></returns>
        [AjaxPro.AjaxMethod]
        public string GetPersonalChatInfoHtml(string user_from)
        {

            string chatinfoHtml = string.Empty;
            if (currentUserID == "")
                return chatinfoHtml;
            Int64 maxChatInfoId = 0;
            DataSet dSet = SqlHelper.Instance.ExecuteQuery("[GetChatInfo] '" + currentUserID + "', '" + user_from + "'");
            if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
            {
                //chatinfoHtml ="<div id=\"MsgDiv\" style =\"  overflow :hidden ; width:100%\">";
                string childHtml = string.Empty;
                foreach (DataRow dRow in dSet.Tables[0].Rows)
                {
                    string color = (dRow["user_from"].ToString() == currentUserID) ? "#308712" : "blue";
                    childHtml = "<div  class =\"chatInfoRecord\">";
                    childHtml += "<span style =\" color:" + color + "; font-weight :bold ;\">" + dRow["name_from"].ToString () + "</span> ";
                    childHtml += "<span style =\"color:Gray\">(" + dRow["sendTime"].ToString() + ")</span> <br />";
                    childHtml += "<div style =\" padding-left :20px;\">";
                    childHtml += dRow["content"].ToString();
                    childHtml += "</div>";
                    childHtml += "</div>";
                    chatinfoHtml += childHtml;      

                    Int64 chatId = Convert.ToInt64(dRow["cbChatInfoId"]);
                    if (chatId > maxChatInfoId)
                        maxChatInfoId = chatId;
                }
                //chatinfoHtml += "</div>";
                cbuser.SetNewMsgPos(currentUserID, maxChatInfoId.ToString(), user_from, false);
                cbuser.SetNewMsgPos(currentUserID, maxChatInfoId.ToString(), user_from, true );
            }
            return chatinfoHtml;
        }

        /// <summary>
        /// 获取公开聊天记录
        /// </summary>
        /// <returns></returns>
        [AjaxPro.AjaxMethod]
        public string GetPublicChatInfoHtml()
        {
            string chatinfoHtml = string.Empty;
            if (currentUserID == "")
                return chatinfoHtml;
            Int64 maxChatInfoId = 0;
            DataSet dSet = SqlHelper.Instance.ExecuteQuery("[GetChatInfo]  '" + currentUserID + "','',1");
            if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
            {
                string childHtml = string.Empty;
                foreach (DataRow dRow in dSet.Tables[0].Rows)
                {
                    if (dRow["user_from"].ToString() != systemUserId)   //非系统消息
                    {
                        string color = (dRow["user_from"].ToString() == currentUserID) ? "#308712" : "blue";
                        childHtml = "<div  class =\"chatInfoRecord\">";
                        childHtml += "<span style =\" color:" + color + "; font-weight :bold ;\">" + dRow["user_from"].ToString() + "</span> ";
                        childHtml += "<span style =\"color:Gray\">(" + dRow["sendTime"].ToString() + ")</span> <br />";
                        childHtml += "<div style =\" padding-left :20px;\">";
                        childHtml += dRow["content"].ToString();
                        childHtml += "</div>";
                        childHtml += "</div>";
                    }
                    else                                              //系统消息
                    {
                        childHtml = "<div  class =\"systemchatInfoRecord\">";
                        childHtml += "<span style =\" color:#9D3C11; font-weight :bold ;\">" + dRow["user_from"].ToString() + "</span> ";
                        childHtml += "<span style =\"color:Gray\">(" + dRow["sendTime"].ToString() + ")</span> <br />";
                        childHtml += "<div style =\" padding-left :20px;\">";
                        childHtml += dRow["content"].ToString();
                        childHtml += "</div>";
                        childHtml += "</div>";
                    }
                    chatinfoHtml += childHtml;

                    Int64 chatId = Convert.ToInt64(dRow["cbChatInfoId"]);
                    if (chatId > maxChatInfoId)
                        maxChatInfoId = chatId;
                }

                cbuser.SetNewMsgPos(currentUserID, maxChatInfoId.ToString(), "", false);
                cbuser.SetNewMsgPos(currentUserID, maxChatInfoId.ToString(), "", true );
            }


            return chatinfoHtml;
        }

        [AjaxPro.AjaxMethod]
        public string GetCurrentUser()
        {
            return AliApi.appUserId;
        }
        #endregion

        #region 绑定分组和右键菜单
        public void BindUserCate()
        {
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "currentuser", "<script type=\"text/javascript\">currentUser = chatblog.usercate.chatroom.GetCurrentUserID().value;</script>", false);
            if (currentUserID == null || currentUserID == "")
                return;

            this.DoorP.InnerHtml = "";
            string childCate = string.Empty;
            string childUser = string.Empty;
            string groupListFilter = string.Empty;

            RuleCode.Table.cbusergroup userGroup = cbusergroup.Find("cbuserid='" + currentUserID + "'", " cbusergroupid ");
            if (userGroup.Count > 0)
            {
                do
                {
                    string sql = "[dbo].[GetUserGroupList] '"+userGroup .cbusergroupid .Value +"'";
                    DataSet dSet = SqlHelper.Instance.ExecuteQuery(sql);
                    int count = dSet.Tables[0].Rows.Count;
                    childCate = "<h2  class=\"h2style\" id=\"" + userGroup.cbusergroupid.Value + "\">" + userGroup.cbname.Value + "<a>(" + count.ToString() + ")</a></h2>";
                    childCate += "<div class=\"content \">"; 
                    if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
                    {                                            
                        foreach (DataRow dRow in dSet.Tables[0].Rows)
                        {
                            string imgStr = string.Empty;
                            if (dRow["chatIsOnLine"] == null || dRow["chatIsOnLine"].ToString ()=="")
                            {
                                imgStr = "<img alt=\"未注册\" title=\"暂时还未注册成系统用户\"  src =\"img/notuser.ico\" />";
                                childCate += "<span class=\"contextMenu0\"  id='" + dRow["g_cbusergroupid"].ToString() + "'title=\"" + dRow["g_cbuserid"].ToString()
                                + "\" ondblclick=\"alert('对不起，该用户还未注册为系统用户，不能聊天！');\">"
                                + imgStr + dRow["g_cbname"].ToString() + "<input value=\"" + dRow["g_cbuserid"].ToString() + "\" type=\"hidden\" /></span>" + "<br />";
                            }
                            else if (dRow["chatIsOnLine"].ToString() == "1")
                            {
                                imgStr = "<img alt=\"在线\" title=\"该用户在线\"  src =\"img/regular_smile.gif\" />";
                                childCate += "<span class=\"contextMenu0\"   id='" + dRow["g_cbusergroupid"].ToString() + "'title=\"" + dRow["g_cbuserid"].ToString()
                                + "\" ondblclick=\"addTab('" + dRow["g_cbuserid"] + "','" + dRow["g_cbname"].ToString() + "');removeImgTimeIdByUserId('" + dRow["g_cbuserid"].ToString() + "');\">"
                                + imgStr + dRow["g_cbname"].ToString() + "<input value=\"" + dRow["g_cbuserid"].ToString() + "\" type=\"hidden\" /></span>" + "<br />";
                            }
                            else if (dRow["chatIsOnLine"].ToString() == "0")
                            {
                                imgStr = "<img alt=\"不在线\" title=\"该用户不在线\"  src =\"img/regular_smile_nocolor.gif\" />";
                                childCate += "<span class=\"contextMenu0\"  id='" + dRow["g_cbusergroupid"].ToString() + "'title=\"" + dRow["g_cbuserid"].ToString()
                                + "\" ondblclick=\"addTab('" + dRow["g_cbuserid"] + "','" + dRow["g_cbname"].ToString() + "');removeImgTimeIdByUserId('" + dRow["g_cbuserid"].ToString() + "');\">"
                                + imgStr + dRow["g_cbname"].ToString() + "<input value=\"" + dRow["g_cbuserid"].ToString() + "\" type=\"hidden\" /></span>" + "<br />";
                            }
                            else
                            {
                                imgStr = "<img alt=\"未知\" title=\"暂时未知用户\"  src =\"img/weizhi.ico\" />";
                                childCate += "<span class=\"contextMenu0\"  id='" + dRow["g_cbusergroupid"].ToString() + "'title=\"" + dRow["g_cbuserid"].ToString()
                                + "\" ondblclick=\"alert('对不起，该用户还未注册为未知用户，不能聊天！');\">"
                                + imgStr + dRow["g_cbname"].ToString() + "<input value=\"" + dRow["g_cbuserid"].ToString() + "\" type=\"hidden\" /></span>" + "<br />";
                            }
                            
                        }                         
                    }
                    childCate += "</div>";                    
                    this.DoorP.InnerHtml += childCate;
                } while (userGroup.Next());
            }

        }
        #endregion

        #region 好友分组Ajax方法
        /// <summary>
        /// 删除组内用户
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="groupid"></param>
        [AjaxPro.AjaxMethod]
        public void DeleteUser(string userid, string groupid)
        {
            cbusergrouplist grouplist = cbusergrouplist.Find("cbuserid='" + userid + "' and cbusergroupid='" + groupid + "'");
            if (grouplist.Count > 0)
            {
                grouplist.CurrentIndex = 0;
                grouplist.Delete();
            }
        }

        /// <summary>
        /// 获取右键菜单 HTML代码
        /// </summary>
        /// <returns></returns>
        [AjaxPro.AjaxMethod]
        public string GetDoorPInnerHtml()
        {
            string html = string.Empty;
            string childCate = string.Empty;
            string childUser = string.Empty;
            string groupListFilter = string.Empty;

            RuleCode.Table.cbusergroup userGroup = cbusergroup.Find("cbuserid='" + currentUserID + "'", " cbusergroupid ");
            if (userGroup.Count > 0)
            {
                do
                {
                    string sql = "[dbo].[GetUserGroupList] '" + userGroup.cbusergroupid.Value + "'";
                    DataSet dSet = SqlHelper.Instance.ExecuteQuery(sql);
                    int count = dSet.Tables[0].Rows.Count;
                    childCate = "<h2  class=\"h2style\" id=\"" + userGroup.cbusergroupid.Value + "\">" + userGroup.cbname.Value + "<a>(" + count.ToString() + ")</a></h2>";
                    childCate += "<div class=\"content \">";
                    if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow dRow in dSet.Tables[0].Rows)
                        {
                            string imgStr = string.Empty;
                            if (dRow["chatIsOnLine"] == null || dRow["chatIsOnLine"].ToString() == "")
                            {
                                imgStr = "<img alt=\"未注册\" title=\"暂时还未注册成系统用户\"  src =\"img/notuser.ico\" />";
                                childCate += "<span class=\"contextMenu0\"  id='" + dRow["g_cbusergroupid"].ToString() + "'title=\"" + dRow["g_cbuserid"].ToString()
                                + "\" ondblclick=\"alert('对不起，该用户还未注册为系统用户，不能聊天！');\">"
                                + imgStr + dRow["g_cbname"].ToString() + "<input value=\"" + dRow["g_cbuserid"].ToString() + "\" type=\"hidden\" /></span>" + "<br />";
                            }
                            else if (dRow["chatIsOnLine"].ToString() == "1")
                            {
                                imgStr = "<img alt=\"在线\" title=\"该用户在线\"  src =\"img/regular_smile.gif\" />";
                                childCate += "<span class=\"contextMenu0\"   id='" + dRow["g_cbusergroupid"].ToString() + "'title=\"" + dRow["g_cbuserid"].ToString()
                                + "\" ondblclick=\"addTab('" + dRow["g_cbuserid"] + "','" + dRow["g_cbname"].ToString() + "');removeImgTimeIdByUserId('" + dRow["g_cbuserid"].ToString() + "');\">"
                                + imgStr + dRow["g_cbname"].ToString() + "<input value=\"" + dRow["g_cbuserid"].ToString() + "\" type=\"hidden\" /></span>" + "<br />";
                            }
                            else if (dRow["chatIsOnLine"].ToString() == "0")
                            {
                                imgStr = "<img alt=\"不在线\" title=\"该用户不在线\"  src =\"img/regular_smile_nocolor.gif\" />";
                                childCate += "<span class=\"contextMenu0\"   id='" + dRow["g_cbusergroupid"].ToString() + "'title=\"" + dRow["g_cbuserid"].ToString()
                                + "\" ondblclick=\"addTab('" + dRow["g_cbuserid"] + "','" + dRow["g_cbname"].ToString() + "');removeImgTimeIdByUserId('" + dRow["g_cbuserid"].ToString() + "');\">"
                                + imgStr + dRow["g_cbname"].ToString() + "<input value=\"" + dRow["g_cbuserid"].ToString() + "\" type=\"hidden\" /></span>" + "<br />";
                            }
                            else
                            {
                                imgStr = "<img alt=\"未知\" title=\"暂时未知用户\"  src =\"img/weizhi.ico\" />";
                                childCate += "<span class=\"contextMenu0\"  id='" + dRow["g_cbusergroupid"].ToString() + "'title=\"" + dRow["g_cbuserid"].ToString()
                                + "\" ondblclick=\"alert('对不起，该用户还未注册为未知用户，不能聊天！');\">"
                                + imgStr + dRow["g_cbname"].ToString() + "<input value=\"" + dRow["g_cbuserid"].ToString() + "\" type=\"hidden\" /></span>" + "<br />";
                            }
                        }
                    }
                    childCate += "</div>";
                    html += childCate;
                } while (userGroup.Next());
            }

            return html;
        }

        /// <summary>
        /// 获取 分组列表HTML代码
        /// </summary>
        /// <returns></returns>
        [AjaxPro.AjaxMethod]
        public string GetGroupListUlHtml(string userid, string oldGroupid)
        {
            string ulHtml = string.Empty;
            RuleCode.Table.cbusergroup userGroup = cbusergroup.Find("cbuserid='" + currentUserID + "'", " cbusergroupid ");
            if (userGroup.Count > 0)
            {
                do
                {
                    ulHtml += "<li id=\"" + userGroup.cbusergroupid.Value + "\" onclick=\"changeGroupId('" + userid + "','" + oldGroupid + "','" + userGroup.cbusergroupid.Value + "')\" >" + userGroup.cbname.Value + "</li>";  //onclick=\"changeGroupId('dddd')\"
                } while (userGroup.Next());
            }
            return ulHtml;
        }

        /// <summary>
        /// 获取 分组列表HTML代码
        /// </summary>
        /// <returns></returns>
        [AjaxPro.AjaxMethod]
        public string GetGroupListSelectHtml(string defaultGroupid)
        {
            string ulHtml = "<table><tr style =\" width :200px; \"><td>选择好友分 类：</td><td style=\"text-align:left;\"><select style =\" width:200px\" id=\"GroupListSelect\">";
            RuleCode.Table.cbusergroup userGroup = cbusergroup.Find("cbuserid='" + currentUserID + "'", " cbusergroupid ");
            if (userGroup.Count > 0)
            {
                do
                {
                    if (defaultGroupid == userGroup.cbusergroupid.Value)
                    {
                        ulHtml += "<option selected=\"true\" id=\"" + userGroup.cbusergroupid.Value + "\">" + userGroup.cbname.Value + "</option>";
                    }
                    else
                    {
                        ulHtml += "<option id=\"" + userGroup.cbusergroupid.Value + "\">" + userGroup.cbname.Value + "</option>";
                    }
                } while (userGroup.Next());
            }
            ulHtml += "</select></td></tr></table>";
            return ulHtml;
        }

        /// <summary>
        /// 更新用户分组信息
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="oldGroupId"></param>
        /// <param name="newGroupId"></param>
        [AjaxPro.AjaxMethod]
        public void UpdateUserGroup(string userid, string oldGroupId, string newGroupId)
        {
            cbusergrouplist grouplist = cbusergrouplist.Find("cbuserid='" + userid + "' and cbusergroupid='" + oldGroupId + "'");
            if (grouplist.Count > 0)
            {
                grouplist.cbusergroupid.Value = newGroupId;
                grouplist.Modify();
            }
        }

        /// <summary>
        /// 重命名好友昵称
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="groupId"></param>
        /// <param name="newName"></param>
        /// <returns></returns>
        [AjaxPro .AjaxMethod ]
        public bool RenameGroupUserName(string userid, string groupId, string newName)
        {
            cbusergrouplist groupList = cbusergrouplist.Find("cbusergroupid='"+groupId +"' and cbuserid='"+userid +"'" );
            if (groupList.Count > 0)
            {
                groupList.cbname.Value = newName;
                groupList.Modify();
                return true ;
            }
            return false;
        }

        [AjaxPro.AjaxMethod]
        public void AddGroup(string cbName)
        {
            cbusergroup group = new cbusergroup();
            group.Init(0);
            group.New();
            group.cbuserid.Value = currentUserID;
            group.cbusergroupid.Value = group.GetRecID().ToString();
            group.cbname.Value = cbName;
            group.Insert();
        }

        [AjaxPro.AjaxMethod]
        public void DeleteGroup(string groupid, string cbName)
        {
            cbusergroup group = cbusergroup.Find("cbusergroupid='" + groupid + "' and cbname='" + cbName + "'");
            if (group.Count > 0)
            {
                group.CurrentIndex = 0;
                group.Delete();
            }
        }

        [AjaxPro.AjaxMethod]
        public bool UpdateGroup(string groupid, string oldName, string newName)
        {
            cbusergroup group = cbusergroup.Find("cbusergroupid='" + groupid + "' and cbname='" + oldName + "'");
            if (group.Count > 0)
            {
                group.cbname.Value = newName;
                group.Modify();
                return true;
            }
            return false;
        }

        [AjaxPro.AjaxMethod]
        public string AddGroupUser(string groupid, string userid, string username, string status)
        {
            try
            {
                string sql = "select * from cbusergrouplist where cbuserid='" + userid + "' and cbusergroupid in (select cbusergroupid from cbusergroup where cbuserid='" + currentUserID + "')";
                DataSet dSet = SqlHelper.Instance.ExecuteQuery(sql);
                if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
                {
                    //MessageBox.Show(this.Page, "该用户已经是好友，不能添加！");
                    return "该用户已经是好友，不能添加！";
                }
                cbusergrouplist grouplist = new cbusergrouplist();
                grouplist.Init(0);
                grouplist.New();
                grouplist.cbname.Value = username;
                grouplist.cbstatus.Value = status;
                grouplist.cbusergroupid.Value = groupid;
                grouplist.cbuserid.Value = userid;
                grouplist.Insert();
            }
            catch (Exception ep)
            {
                return ep.Message;
            }
            return "";
        }

        [AjaxPro.AjaxMethod]
        public int GetGroupUserList(string groupid)
        {
            string filter = "cbusergroupid='" + groupid + "' ";
            cbusergrouplist grouplist = cbusergrouplist.Find(filter);
            return grouplist.Count;
        }
        #endregion

        #region 聊天对象相关
        /// <summary>
        /// 发起聊天
        /// </summary>
        /// <param name="chatUser_To"></param>
        /// <returns></returns>
        [AjaxPro .AjaxMethod ]
        public string RaiseChat(string chatUser_To)
        {
            if (currentUserID == "" || currentUserID == null)
                return string.Empty;

            string result = string.Empty;
            ChatUser chatUserTo = new ChatUser();            
            ChatUser chatUserFrom = new ChatUser();     
            bool exsitTo = false;
            bool exsitFrom = false;

            chatUserFrom.Role = ChatUserRole.Sender;
            chatUserFrom.isOnline = true;
            chatUserFrom.UserId = AliApi.appUserId;
            
            foreach (ChatUser chatuser in Util.ChatUserPairs.Keys )
            {
                if (chatuser.UserId == chatUser_To && Util.ChatUserPairs[chatuser].UserId == AliApi.appUserId  )
                {
                    exsitTo = true;
                    chatUserTo  = chatuser;
                    break;
                }

                if (chatuser.UserId == AliApi.appUserId && Util.ChatUserPairs[chatuser].UserId == chatUser_To)
                {
                    exsitFrom = true;
                    chatUserFrom = Util.ChatUserPairs[chatuser];
                    break;
                }
            }
            if ((!exsitTo)&& (!exsitFrom ))
            {
                chatUserTo.Role = ChatUserRole.Receiver;
                chatUserTo.UserId = chatUser_To;
                chatUserTo.isOnline = false;

                cbuser user = cbuser.Find("cbuserid='" + chatUser_To + "'");
                if (user.Count > 0)
                {
                    chatUserTo.isOnline = (user.chatIsOnLine.Value == RuleCode.Enum.BooleanEnum.Yes);
                    chatUserTo.UserId = user.cbuserid.Value;
                }
                
                Util.ChatUserPairs.Add(chatUserFrom, chatUserTo);
            }             

            return result;
        }

        /// <summary>
        /// 获取 最新发消息的用户
        /// </summary>
        /// <returns></returns>
        [AjaxPro .AjaxMethod ]
        public string[] getNewMsgUsers()
        {               
            List<string> msgUsers = new List<string>();
            if (currentUserID != "")
            {
                string sqlText = "dbo.[GetNewMsgUsers] '" + currentUserID + "'";
                DataSet dSet = SqlHelper.Instance.ExecuteQuery(sqlText );
                if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dRow in dSet.Tables[0].Rows)
                        msgUsers.Add(dRow["user_from"].ToString());
                }

            }
            return msgUsers.ToArray ();
        }

        [AjaxPro .AjaxMethod ]
        public string[] getOnlineUsers(bool chatIsOnline)
        {
            List<string> onlineUsers = new List<string>();
            if (AliApi.appUserId != string.Empty && AliApi.appUserId != null)
            {
                string sqlText = "dbo.[GetChatUserStatus] '"+AliApi .appUserId +"',"+(chatIsOnline?"1":"0");
                DataSet dSet = SqlHelper.Instance.ExecuteQuery(sqlText);
                if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dRow in dSet.Tables[0].Rows)
                    {
                        onlineUsers.Add(dRow["userid_to"].ToString());
                    }
                }
            }
            return onlineUsers.ToArray ();
        }

        /// <summary>
        /// 获取所有好友的状态
        /// </summary>
        /// <returns></returns>
        [AjaxPro .AjaxMethod ]
        public string getAllUserStatus()
        {
            string result = string.Empty;
            string sqlText = "dbo.[GetChatUserStatus] '" + AliApi.appUserId + "',-1";
            DataSet dSet = SqlHelper.Instance.ExecuteQuery(sqlText);
            if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dRow in dSet.Tables[0].Rows)
                {
                    result += dRow["userid_to"].ToString() + "=";
                    if (dRow["chatIsOnline"] == null )
                    {
                        result += "";
                    }
                    else
                    {
                        result += dRow["chatIsOnline"].ToString();
                    }
                    result += ";";
                }
            }
            return result;
        }

        [AjaxPro .AjaxMethod ]
        public void LoginOut()
        {
            if (AliApi.appUserId != null && AliApi.appUserId != string.Empty && Util.useLoginOut ==true )
            {
                cbuser user = cbuser.Find("cbuserid='"+AliApi .appUserId +"'");
                if (user.Count > 0 )
                {
                    user.chatIsOnLine.Value = RuleCode.Enum.BooleanEnum.No;
                    user.cbChatAddress.Value = "";
                    user.Modify();
                }
            }
        }
        #endregion

    }


}
